﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using SAP.WebServices;
using System.Collections;
using System.Globalization;
using System.Net;
using System.Drawing;

namespace SAP
{
    public partial class PatientMaster : System.Web.UI.Page
    {
        private GeneralFunctions GF = new GeneralFunctions(HttpContext.Current.User.Identity.Name);
        public static DataTable dtHeader;
        public static DataTable dtContactPerson;
        public static DataTable dtAddress;
        public static DataTable dtAttachment;
        public static DataTable dtHistory;
        
        private string TblHeaderName = "OCRD";
        private string TblAddress = "CRD1";
        private string TblContact = "OCPR";
        private string DocType = "2";
        public static string KeepColumsHeader = "";
        private string IISServerPhotoPath = "~/ServerPhoto/"; //on IIS

        public static string UNCServerPhotoPath;
        public static string UNCServerAttachmentPath; 
        #region "Event"
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
                ClearScreen();
                lvContactPerson.DataSource = dtContactPerson;
                lvContactPerson.DataBind();
                lvAddress.DataSource = dtAddress;
                lvAddress.DataBind();

                MasterData masterDataWS = new MasterData();
                DataSet dsMaster;
                dsMaster = masterDataWS.GetCompanySetting(User.Identity.Name);

                UNCServerPhotoPath = @dsMaster.Tables[0].Rows[0]["BitmapPath"].ToString();
                UNCServerAttachmentPath = @dsMaster.Tables[0].Rows[0]["AttachPath"].ToString();

                dsMaster = masterDataWS.GetShippingType(User.Identity.Name);
                if (dsMaster != null)
                {
                    dsMaster.Tables[0].Rows.Add("-1", "");
                    ddlShipping.DataSource = dsMaster.Tables[0];
                    ddlShipping.DataTextField = "TrnspName";
                    ddlShipping.DataValueField = "TrnspCode";
                    ddlShipping.DataBind();
                    ddlShipping.SelectedValue = "-1";
                }

                dsMaster = masterDataWS.GetBPGroup(ddlCardType.SelectedValue, User.Identity.Name);
                if (dsMaster.Tables.Count > 0)
                {
                    ddlBPGroup.DataSource = dsMaster.Tables[0];
                    ddlBPGroup.DataTextField = "GroupName";
                    ddlBPGroup.DataValueField = "GroupCode";
                    ddlBPGroup.DataBind();
                }

                dsMaster = masterDataWS.GetIndustry(User.Identity.Name);
                if (dsMaster.Tables.Count > 0)
                {
                    ddlIndustry.DataSource = dsMaster.Tables[0];
                    ddlIndustry.DataTextField = "IndName";
                    ddlIndustry.DataValueField = "IndCode";
                    ddlIndustry.DataBind();
                }

                dsMaster = masterDataWS.GetBPCurrency("", User.Identity.Name);
                if (dsMaster.Tables.Count > 0)
                {
                    dsMaster.Tables[0].Rows.Add("##", "All Currency");
                    ddlCurrency.DataSource = dsMaster.Tables[0];
                    ddlCurrency.DataTextField = "CurrName";
                    ddlCurrency.DataValueField = "CurrCode";
                    ddlCurrency.DataBind();
                    ddlCurrency.Items.FindByValue("##").Selected = true;
                }

                if (ddlCardType.SelectedValue == "S")
                    dsMaster = masterDataWS.GetSeries(User.Identity.Name, DocType, "S");
                else
                    dsMaster = masterDataWS.GetSeries(User.Identity.Name, DocType, "C");
                if (dsMaster.Tables.Count > 0)
                {
                    ddlSeries.DataSource = dsMaster.Tables[0];
                    ddlSeries.DataTextField = "SeriesName";
                    ddlSeries.DataValueField = "Series";
                    ddlSeries.DataBind();
                }

               

                string cardcode = Request.QueryString["cardcode"];
                if (!String.IsNullOrEmpty(cardcode))
                {
                    LoadData(cardcode);
                }
                else
                {
                    LoadDefault();
                }
            }
        }
        protected void btnAdd_Click(object sender, ImageClickEventArgs e)
        {
            if (txtCardCode.Text == "")
            {
                Session["errorMessage"] = "Missing Card Code";
                Session["requestXML"] = "";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                    "Main.setMasterMessage('Missing Card Code','');", true);
                return;
            }

            String requestXML = _collectData();
            SAP.WebServices.Transaction ts = new WebServices.Transaction();
            DataSet ds = ts.CreateMarketingDocument(requestXML, User.Identity.Name, DocType, "", false);
            if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
            {
                Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                Session["requestXML"] = requestXML;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                    "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
            }
            else
            {
                Session["successMessage"] = "Operation complete sucessful!";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                   "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);

                LoadData(txtCardCode.Text);
            }
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                              "Dialog.hideLoader();", true);
        }
        protected void ddlCardType_SelectedIndexChanged(object sender, EventArgs e)
        {
            MasterData masterDataWS = new MasterData();
            DataSet dsMaster;
            dsMaster = masterDataWS.GetBPGroup(ddlCardType.SelectedValue, User.Identity.Name);
            ddlBPGroup.DataSource = dsMaster.Tables[0];
            ddlBPGroup.DataTextField = "GroupName";
            ddlBPGroup.DataValueField = "GroupCode";
            ddlBPGroup.DataBind();

            if (ddlCardType.SelectedValue == "S")
                dsMaster = masterDataWS.GetSeries(User.Identity.Name, DocType, "S");
            else
                dsMaster = masterDataWS.GetSeries(User.Identity.Name, DocType, "C");
            if (dsMaster.Tables.Count > 0)
            {
                ddlSeries.DataSource = dsMaster.Tables[0];
                ddlSeries.DataTextField = "SeriesName";
                ddlSeries.DataValueField = "Series";
                ddlSeries.DataBind();
            }
        }
        protected void ddlSeries_SelectedIndexChanged(object sender, EventArgs e)
        {
            GenerateSeri();
        }
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                       case "EditProjectCallBack":
                            //Project prj = Session["chosenProject"] as Project;
                            //if (prj != null)
                            //{
                            //    this.txtProject.Text = prj.PrjCode;
                            //}
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }
        protected void btnActivity_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("/BusinessPartner/Appointment.aspx?CardCode=" + txtCardCode.Text + "&CardName=" + txtCardName.Text);
        }
        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            string sSavePath = UNCServerAttachmentPath;

            if (FileUpload1.PostedFile != null)
            {
                HttpPostedFile myFile = FileUpload1.PostedFile;
                int nFileLen = myFile.ContentLength;
                if (nFileLen == 0)
                {
                    lblOutput.Text = "No file was uploaded.";
                    return;
                }
                byte[] myData = new Byte[nFileLen];
                myFile.InputStream.Read(myData, 0, nFileLen);
                string sFilename = System.IO.Path.GetFileName(myFile.FileName);

                System.IO.FileStream newFile = new System.IO.FileStream(sSavePath + sFilename, System.IO.FileMode.Create);
                newFile.Write(myData, 0, myData.Length);
                newFile.Close();
                DataRow dr = dtAttachment.NewRow();

                dr["No"] = dtAttachment.Rows.Count + 1;
                dr["FileName"] = System.IO.Path.GetFileNameWithoutExtension(FileUpload1.FileName);// "SALES_0300200302002_1_1946_1305080025";
                dr["FileExt"] = System.IO.Path.GetExtension(sFilename).Replace(".", "");
                dr["srcPath"] = sSavePath ;
                dtAttachment.Rows.Add(dr);

                lvAttachments.DataSource = dtAttachment;
                lvAttachments.DataBind();
            }
        }
        protected void lvHistory_ItemCommand(object sender, ListViewCommandEventArgs e)
        {

        }
        protected void btnUpdate_Click(object sender, ImageClickEventArgs e)
        {
            if (txtCardCode.Text == "")
            {
                Session["errorMessage"] = "Missing Card Code";
                Session["requestXML"] = "";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                    "Main.setMasterMessage('Missing Card Code','');", true);
                return;
            }

            String requestXML = _collectData();
            SAP.WebServices.Transaction ts = new WebServices.Transaction();
            DataSet ds = ts.CreateMarketingDocument(requestXML, User.Identity.Name, DocType, txtCardCode.Text, true);
            if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
            {
                Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                Session["requestXML"] = requestXML;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                    "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
            }
            else
            {
                Session["successMessage"] = "Operation complete sucessful!";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                   "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);

                LoadData(txtCardCode.Text);
            }
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                              "Dialog.hideLoader();", true);
        }
        protected void ImageButton1_Click(object sender, EventArgs e)
        {

        }

        protected void btnView_Click(object sender, EventArgs e)
        {
            
            
            // Initialize variables
            string sSavePath;

            // Set constant values
            sSavePath = UNCServerPhotoPath;// "images/";
            //sSavePath = "images/";

            // If file field isn’t empty
            if (FileUpload2.PostedFile != null)
            {
                // Check file size (mustn’t be 0)
                HttpPostedFile myFile = FileUpload2.PostedFile;
                int nFileLen = myFile.ContentLength;
                if (nFileLen == 0)
                {
                    lblOutput.Text = "No file was uploaded.";
                    return;
                }

                // Check file extension (must be JPG)
                if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
                {
                    lblOutput.Text = "The file must have an extension of JPG";
                    return;
                }

                // Read file into a data stream
                byte[] myData = new Byte[nFileLen];
                myFile.InputStream.Read(myData, 0, nFileLen);

                // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an 
                // incremental numeric until it is unique
                string sFilename = System.IO.Path.GetFileName(myFile.FileName);
                int file_append = 0;
                //Server.MapPath(sSavePath + sFilename)
                while (System.IO.File.Exists(sSavePath + sFilename))
                {
                    file_append++;
                    sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                     + file_append.ToString() + ".jpg";
                }

                // Save the stream to disk
                System.IO.FileStream newFile
                        = new System.IO.FileStream(sSavePath + sFilename,
                                                   System.IO.FileMode.Create);
                newFile.Write(myData, 0, myData.Length);
                newFile.Flush();
                newFile.Close();

                imgPhoto.ImageUrl = IISServerPhotoPath+sFilename;// sSavePath + sFilename;
            }


        }
        public bool ThumbnailCallback()
        {
            return false;
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindCategories(txtFilter.Text);
        }
        private void BindCategories(string CategoryFilter)
        {

            try
            {
                // Simple created a table to bind with Grid view and populated it with data.
                DataTable gridTable = new DataTable("Items");
                gridTable.Columns.Add("DocEntry");
                gridTable.Columns.Add("WhsName");
                gridTable.Columns.Add("DocDate");
                gridTable.Columns.Add("SlpName");
                gridTable.Columns.Add("U_Treatment");
                gridTable.Columns.Add("U_Diagnosis");
                DataRow dr;
                int i = 0;
                foreach (DataRow row in dtHistory.Rows)
                {
                    if (("" + row[0].ToString() + row[5].ToString() + row[4].ToString() + row[3].ToString() + row[2].ToString() + row[1].ToString()).Trim().IndexOf(CategoryFilter.Trim()) >= 0)
                    {
                        dr = gridTable.NewRow();
                        dr["DocEntry"] = row[1].ToString();
                        dr["WhsName"] = row[2].ToString();
                        dr["DocDate"] = row[3].ToString();
                        dr["SlpName"] = row[4].ToString();
                        dr["U_Treatment"] = row[5].ToString();
                        dr["U_Diagnosis"] = row[6].ToString();
                        gridTable.Rows.Add(dr);
                    }
                    i++;
                }
                lvHistory.DataSource = gridTable;
                lvHistory.DataBind();
                //editEmployeeUpdatePanel.Update();
            }
            catch (Exception)
            {

            }
            finally
            {

            }
        }
        #endregion

        #region "Functions"
        private void LoadData(string Cardcode)
        {
            try
            {
                Transaction trx = new Transaction();
                dtHeader = trx.GetMarketingDocument_ReturnDS(DocType, Cardcode, User.Identity.Name).Tables[0];
                if (dtHeader.Rows.Count == 0)
                    Cardcode = "";
                DataSet ds = trx.GetMarketingDocument_ReturnDS(DocType, Cardcode, User.Identity.Name);
                dtHeader = ds.Tables[0];

                DataRow dr = dtHeader.Rows[0];
                txtCardCode.Text=dr["CardCode"].ToString();
                txtCardName.Text = dr["CardName"].ToString();
                txtFName.Text=dr["CardFName"].ToString();
                txtLicTradNum.Text=dr["LicTradNum"].ToString() ;
                txtTel1.Text=dr["Phone1"].ToString() ;
                txtTel2.Text=dr["Phone2"].ToString() ;
                txtPassword.Text = dr["Password"].ToString();
                txtAllergy.Text = dr["U_Allergy"].ToString();
                txtNotes.Text = dr["U_Notes"].ToString();
                txtChannelBP.Text = dr["ChannlBP"].ToString();
                txtFatherCard.Text = dr["FatherCard"].ToString();
                ddlCardType.SelectedValue = dr["CardType"].ToString();
                ddlCurrency.SelectedValue = dr["currency"].ToString();
                ddlBPGroup.SelectedValue = dr["GroupCode"].ToString();
                txtNotesSAP.Text = dr["Notes"].ToString();

                txtMobile.Text=dr["Cellular"].ToString();
                txtFax.Text=dr["Fax"].ToString();
                txtEmail.Text=dr["E_Mail"].ToString();
                //txtWebsite.Text=dr["IntrntSite"].ToString();
                ddlShipping.SelectedValue = dr["ShipType"].ToString();
                ddlIndustry.SelectedValue = dr["IndustryC"].ToString();
                txtIDNo2.Text=dr["AddID"].ToString();
                //txtFederalTax.Text=dr["VatIdUnCmp"].ToString();

                txtAcctBalance.Text = GF.FormatNumeric(dr["Balance"].ToString(), "SumDec");
                if (dr["CardType"].ToString() == "S")
                {
                    trOrder.Visible = false;
                    trDelivery.Visible = false;
                    trOppor.Visible = false;
                }
                else
                {
                    trOrder.Visible = true;
                    trDelivery.Visible = true;
                    trOppor.Visible = true;
                    txtOrder.Text = GF.FormatNumeric(dr["OrdersBal"].ToString(), "SumDec");
                    txtDelivery.Text = GF.FormatNumeric(dr["DNotesBal"].ToString(), "SumDec");
                    txtOpportunity.Text = dr["OprCount"].ToString();            
                }

                txtMedialBalance.Text = GF.FormatNumeric(dr["U_MedicalBalance"].ToString(), "SumDec");
                txtEmail.Text = dr["E_mail"].ToString();
                txtRemark.Text = dr["Free_Text"].ToString();
                txtAlias.Text = dr["AliasName"].ToString();

                ddlSeries.SelectedValue = dr["Series"].ToString();
                //----------load contact person---------------
                dtContactPerson = trx.GetMarketingDocument_ReturnDS("11", Cardcode, User.Identity.Name).Tables[0];
                lvContactPerson.DataSource = dtContactPerson;
                lvContactPerson.DataBind();
            
                //----------load address----------------------
                dtAddress =ds.Tables[1];
                lvAddress.DataSource = dtAddress;
                lvAddress.DataBind();

                //----------load medical history-------------
                Reports rp = new Reports();

                dtHistory = rp.BP_SalesHistory_Detail(User.Identity.Name,Cardcode).Tables[0];
                lvHistory.DataSource = dtHistory;
                lvHistory.DataBind();

                //----------load attachment-------------
                dtAttachment=rp.BP_Attachment_List(User.Identity.Name,Cardcode).Tables[0];
                lvAttachments.DataSource=dtAttachment;
                lvAttachments.DataBind();

                //-----------load picture------------------
                imgPhoto.ImageUrl = IISServerPhotoPath + dr["U_Picture"].ToString();

                //-----------Load contract-----------------
                DataTable dt = rp.BP_LoadContract(User.Identity.Name, Cardcode).Tables[0];
                lvContract.DataSource = dt;
                lvContract.DataBind();
                if (dt.Rows.Count>0)
                {
                    txtConCompany.Text = dt.Rows[0]["U_CompName"].ToString();
                txtConRemark.Text = dt.Rows[0]["U_Remarks"].ToString();
                }
                

                SetNavigatorURL(txtCardCode.Text);
                SetScreenStatus("Update");
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                    "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }
        public String _collectData()
        {
            try
            {
                dtHeader = GF.ConvertDataTable_RemoveCols(dtHeader, KeepColumsHeader);

                DataRow dr = dtHeader.Rows[0];

                CultureInfo ivC = new System.Globalization.CultureInfo("es-US");

                dr["CardCode"] = txtCardCode.Text;
                dr["CardName"] = txtCardName.Text;
                dr["CardFName"] = txtFName.Text;
                dr["LicTradNum"] = txtLicTradNum.Text;
                dr["Phone1"] = txtTel1.Text;
                dr["Phone2"] = txtTel2.Text;
                dr["Password"] = txtPassword.Text;
                dr["Free_Text"] = txtRemark.Text;
                dr["CardType"] = ddlCardType.SelectedItem.Value.ToString();
                dr["GroupCode"] = ddlBPGroup.SelectedItem.Value.ToString();
                dr["Currency"] = ddlCurrency.SelectedItem.Value.ToString();
                dr["Cellular"] = txtMobile.Text;
                dr["Fax"] = txtFax.Text;
                dr["E_Mail"] = txtEmail.Text;
                if(ddlShipping.SelectedItem!=null)
                    dr["ShipType"] = ddlShipping.SelectedItem.Value.ToString();
                if(ddlIndustry.SelectedItem!=null)
                    dr["IndustryC"] = ddlIndustry.SelectedItem.Value.ToString();
                dr["AddID"] = txtIDNo2.Text;

                dr["Series"] = ddlSeries.SelectedItem.Value;
                dr["U_UserID"] = User.Identity.Name;

                dr["U_Allergy"] = txtAllergy.Text;
                dr["U_Notes"] =txtNotes.Text;
                //Uri uri = new Uri(imgPhoto.ImageUrl);
                //string fileName = uri.Segments.Last();

                dr["U_Picture"] = System.IO.Path.GetFileName(imgPhoto.ImageUrl);
                //dr["AtcEntry"] = "6";
                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");

                //if (dtAttachment.Rows.Count > 0)
                //{
                //    SAP.WebServices.Transaction ts = new WebServices.Transaction();
                //    ds = ts.AddAttachment(User.Identity.Name, dtAttachment);
                //    if ((int)ds.Tables[0].Rows[0]["ErrCode"] == 0)
                //    {
                //        dr["AtcEntry"] = ds.Tables[0].Rows[0]["ErrMsg"];
                //    }
                //}

               
                dtHeader.TableName = TblHeaderName;
                dtAddress.TableName = TblAddress;
                dtContactPerson.TableName = TblContact;
                ds.Tables.Add(dtHeader.Copy());
                
                
                return objInfo.ToXMLStringFromDS(DocType, ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
                return "";
            }
        }
        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnAdd.Visible = true;
                    btnUpdate.Visible = false;
                    btnAddAddress.Visible = true;
                    btnAddContact.Visible = true;
                    btnActivity.Visible = false;
                    break;
                case "Update":
                    btnAdd.Visible = false;
                    btnUpdate.Visible = true;
                    txtCardCode.Enabled = false;
                    btnAddAddress.Visible = false;
                    btnAddContact.Visible = false;
                    btnActivity.Visible = true;
                    break;
                case "Close":
                    btnAdd.Visible = false;
                    btnUpdate.Visible = false;
                    txtCardCode.Enabled = false;
                    btnAddAddress.Visible = false;
                    btnAddContact.Visible = false;
                    btnActivity.Visible = true;
                    break;
            }
        }
        private void ClearScreen()
        {
            //------------------create header table-----------------------------
            dtHeader = new DataTable("OCRD");
            dtHeader.Columns.Add("CardType");
            dtHeader.Columns.Add("CardCode");
            dtHeader.Columns.Add("CardName");
            dtHeader.Columns.Add("CardFName");
            dtHeader.Columns.Add("LicTradNum");
            dtHeader.Columns.Add("Phone1");
            dtHeader.Columns.Add("Phone2");
            dtHeader.Columns.Add("Password");
            dtHeader.Columns.Add("Free_Text");
            dtHeader.Columns.Add("GroupCode");
            dtHeader.Columns.Add("Currency");
            dtHeader.Columns.Add("Cellular");
            dtHeader.Columns.Add("Fax");
            dtHeader.Columns.Add("E_Mail");
            dtHeader.Columns.Add("IntrntSite");
            dtHeader.Columns.Add("ShipType");
            dtHeader.Columns.Add("IndustryC");
            dtHeader.Columns.Add("AddID");
            dtHeader.Columns.Add("VatIdUnCmp");
            dtHeader.Columns.Add("Series"); 
            dtHeader.Columns.Add("U_UserID");
            dtHeader.Columns.Add("U_Allergy");
            dtHeader.Columns.Add("U_Notes");
            dtHeader.Columns.Add("U_Picture");
            dtHeader.Columns.Add("AtcEntry");
            
            dtHeader.Rows.Add();
            KeepColumsHeader = GF.BuildKeepColumnStr(dtHeader);

            //---------------create contact person table-------------------------
            dtContactPerson = new DataTable("OCPR");
            dtContactPerson.Columns.Add("No");
            dtContactPerson.Columns.Add("Name");
            dtContactPerson.Columns.Add("FirstName");
            dtContactPerson.Columns.Add("MiddleName");
            dtContactPerson.Columns.Add("LastName");
            dtContactPerson.Columns.Add("Title");
            dtContactPerson.Columns.Add("Position");
            dtContactPerson.Columns.Add("Address");
            dtContactPerson.Columns.Add("Tel1");
            dtContactPerson.Columns.Add("Tel2");
            dtContactPerson.Columns.Add("Cellolar");
            dtContactPerson.Columns.Add("E_MailL");

            //------------------create address table-------------------
            dtAddress = new DataTable("CRD1");
            dtAddress.Columns.Add("No");
            dtAddress.Columns.Add("Address");
            dtAddress.Columns.Add("CardCode");
            dtAddress.Columns.Add("Street");
            dtAddress.Columns.Add("AdresType");
            dtAddress.Columns.Add("StreetNo");
            dtAddress.Columns.Add("Building");
            //------------------create History table-------------------
            dtAddress = new DataTable("History");
            dtAddress.Columns.Add("No");
            dtAddress.Columns.Add("ItemCode");
            dtAddress.Columns.Add("Description");

            //-----------------create attachment table-----------------
            dtAttachment = new DataTable("Attachment");
            dtAttachment.Columns.Add("No");
            dtAttachment.Columns.Add("FileName");
            dtAttachment.Columns.Add("FileExt");
            dtAttachment.Columns.Add("srcPath");
            
            //--------------clear text-------------------
            txtCardCode.Text = "";
            txtCardName.Text = "";
            txtFName.Text = "";
            txtLicTradNum.Text = "";
            txtTel1.Text = "";
            txtTel2.Text = "";
            txtPassword.Text = "";
            txtMobile.Text = "";
            txtFax.Text = "";
            txtEmail.Text = "";
            txtMedialBalance.Text = "";
            txtAcctBalance.Text ="";
            txtOrder.Text = "";
            txtDelivery.Text = "";
            txtOpportunity.Text = "";
            txtEmail.Text = "";
            txtRemark.Text = "";

            SetNavigatorURL("");
            SetScreenStatus("New");
        }
        protected void SetNavigatorURL(string CurrentKey)
        {
            GetDefault df = new GetDefault();
            DataSet nav = df.GetNextPreviousID(DocType, User.Identity.Name, "OCRD", "cardcode", CurrentKey);
            if (nav != null)
            {
                this.linkFirst.NavigateUrl = "/BusinessPartner/PatientMaster.aspx?cardcode=" + nav.Tables[0].Rows[0]["Fir"].ToString();
                this.linkNext.NavigateUrl = "/BusinessPartner/PatientMaster.aspx?cardcode=" + nav.Tables[0].Rows[0]["Nex"].ToString();
                this.linkPrevious.NavigateUrl = "/BusinessPartner/PatientMaster.aspx?cardcode=" + nav.Tables[0].Rows[0]["Pre"].ToString();
                this.linkLast.NavigateUrl = "/BusinessPartner/PatientMaster.aspx?cardcode=" + nav.Tables[0].Rows[0]["Las"].ToString();
            }
            this.linkNew.NavigateUrl = "/BusinessPartner/PatientMaster.aspx?cardcode=";
        }
        protected void LoadDefault()
        {
            if (ddlSeries.Items.FindByText("CRM") != null)
            {
                ddlSeries.Items.FindByText("CRM").Selected = true;
                GenerateSeri();
            }
            
        }
        protected void GenerateSeri()
        {
            MasterData masterDataWS = new MasterData();
            DataSet dsMaster;
            dsMaster = masterDataWS.GetSeries(User.Identity.Name, "2", ddlCardType.SelectedValue);
            DataView dv = new DataView(dsMaster.Tables[0]);
            dv.RowFilter = "Series=" + ddlSeries.SelectedValue;
            if (dv.Count > 0)
            {
                if (!string.IsNullOrEmpty(dv[0]["NextNumber"].ToString()))
                {
                    txtCardCode.Enabled = false;
                    string code = "";
                    code = dv[0]["BeginStr"].ToString();
                    for (int i = 0; i < (int)(dv[0]["NumSize"]) - dv[0]["NextNumber"].ToString().Length; i++)
                        code = code + "0";

                    code = code + dv[0]["NextNumber"].ToString();
                    txtCardCode.Text = code;
                }
                else
                {
                    txtCardCode.Enabled = true;
                    txtCardCode.Text = "";
                }
            }
            else
            {
                txtCardCode.Enabled = true;
                txtCardCode.Text = "";
            }
        }
       
        #endregion

        #region "Contact"
        private void _cancelAddNewContact()
        {
            this.lvContactPerson.InsertItemPosition = InsertItemPosition.None;
            this.btnAddContact.Enabled = true;
            this.lvContactPerson.DataBind();
        }
        private void SetControlsStatus_Contact(string asStatus)
        {
            switch (asStatus)
            {
                case "Add":
                    btnUpdate.Enabled = btnAdd.Enabled = btnAddContact.Enabled = false;
                    break;
                case "Edit":
                     btnUpdate.Enabled =btnAdd.Enabled = btnAddContact.Enabled = false;
                    break;
                case "Update":
                     btnUpdate.Enabled =btnAdd.Enabled = btnAddContact.Enabled = true;
                    break;
                case "Save":
                     btnUpdate.Enabled =btnAdd.Enabled = btnAddContact.Enabled = true;
                    break;
            }
        }
        private void ResetLineNo_Contact()
        {
            int i = 0;
            foreach (DataRow row in dtContactPerson.Rows)
                row["No"] = ++i;
        }
        protected void lvAttachments_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            ListViewItem lvi = e.Item;
            switch (e.CommandName)
            {
                case "DeleteItem":
                    //delete in server
                    Label lblNo = (Label)lvi.FindControl("No");
                    break;
            }
        }
        protected void lvContactPerson_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                ListViewItem lvi = e.Item;
                switch (e.CommandName)
                {
                    case "CancelAddNew":
                        this._cancelAddNewContact();
                        this.lvContactPerson.DataBind();
                        break;
                    case "CancelUpdate":
                        this.lvContactPerson.EditIndex = -1;
                        this.lvContactPerson.DataSource = dtContactPerson;
                        this.lvContactPerson.DataBind();
                        break;
                    case "Update":
                        // update new data to dt
                        if (string.IsNullOrEmpty(((TextBox)lvi.FindControl("lblName")).Text)) return;

                        Label lblNo = (Label)lvi.FindControl("lblNo");
                        foreach (DataRow row in dtContactPerson.Rows)
                        {
                            if (row["No"].ToString().Equals(lblNo.Text)) // update currentrow into data table
                            {
                                row["Name"] = ((TextBox)lvi.FindControl("lblName")).Text;
                                row["FirstName"] = ((TextBox)lvi.FindControl("lblFirstName")).Text;
                                row["MiddleName"] = ((TextBox)lvi.FindControl("lblMiddleName")).Text;
                                row["LastName"] = ((TextBox)lvi.FindControl("lblLastName")).Text;
                                row["Title"] = ((TextBox)lvi.FindControl("lblTitle")).Text;
                                row["Position"] = ((TextBox)lvi.FindControl("lblPosition")).Text;
                                row["Address"] = ((TextBox)lvi.FindControl("lblAddress")).Text;
                                row["Tel1"] = ((TextBox)lvi.FindControl("lblTel1")).Text;
                                row["Tel2"] = ((TextBox)lvi.FindControl("lblTel2")).Text;
                                row["Cellolar"] = ((TextBox)lvi.FindControl("lblCellolar")).Text;
                                row["E_MailL"] = ((TextBox)lvi.FindControl("lblE_MailL")).Text;
                                break;
                            }
                        }
                        this.lvContactPerson.EditIndex = -1;
                        this.lvContactPerson.DataSource = dtContactPerson;
                        this.lvContactPerson.DataBind();
                        SetControlsStatus_Contact("Update");
                        break;

                    case "DeleteItem":
                        // delete data and update dt
                        int i_idx = e.Item.DataItemIndex;
                        dtContactPerson.Rows.RemoveAt(i_idx);
                        this.lvContactPerson.EditIndex = -1;
                        ResetLineNo_Contact();
                        this.lvContactPerson.DataSource = dtContactPerson;
                        this.lvContactPerson.DataBind();
                        SetControlsStatus_Contact("Update");
                        break;

                    default: break;
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }

        protected void lvContactPerson_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            this.lvContactPerson.EditIndex = e.NewEditIndex;
            this.lvContactPerson.DataSource = dtContactPerson;
            this.lvContactPerson.DataBind();
            SetControlsStatus_Contact("Edit");
        }

        protected void lvContactPerson_ItemInserted(object sender, ListViewInsertedEventArgs e)
        {
            _cancelAddNewContact();
        }

        protected void lvContactPerson_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            Label TextBox = (Label)lvContactPerson.Items[e.ItemIndex].FindControl("lblName");
            if (string.IsNullOrEmpty(TextBox.Text))
            {
                e.Cancel = true;
                return;
            }
            this.lvContactPerson.EditIndex = -1;
            this.lvContactPerson.DataSource = dtContactPerson;
            this.lvContactPerson.DataBind();
        }

        protected void btnAddContact_Click(object sender, EventArgs e)
        {
            int iNo = dtContactPerson.Rows.Count + 1;
            dtContactPerson.Rows.Add(iNo, "", "", "", "", "", "", "", "", "", "", "");
            this.lvContactPerson.DataSource = dtContactPerson;

            this.lvContactPerson.EditIndex = iNo - 1;
            this.lvContactPerson.DataBind();
            SetControlsStatus_Contact("Add");
        }

        protected void ContactPager_PreRender(object sender, EventArgs e)
        {
            lvContactPerson.DataSource = dtContactPerson;
            lvContactPerson.DataBind();
        }
        #endregion

        #region "Address"
        private void _cancelAddNewAdd()
        {
            this.lvAddress.InsertItemPosition = InsertItemPosition.None;
            this.btnAddAddress.Enabled = true;
            this.lvAddress.DataBind();
        }
        private void SetControlsStatus_Add(string asStatus)
        {
            switch (asStatus)
            {
                case "Add":
                    btnUpdate.Enabled = btnAdd.Enabled = btnAddAddress.Enabled = false;
                    break;
                case "Edit":
                    btnUpdate.Enabled = btnAdd.Enabled = btnAddAddress.Enabled = false;
                    break;
                case "Update":
                    btnUpdate.Enabled = btnAdd.Enabled = btnAddAddress.Enabled = true;
                    break;
                case "Save":
                    btnUpdate.Enabled = btnAdd.Enabled = btnAddAddress.Enabled = true;
                    break;
            }
        }
        private void ResetLineNo_Add()
        {
            int i = 0;
            foreach (DataRow row in dtAddress.Rows)
                row["No"] = ++i;
        }
        protected void btnAddAddress_Click(object sender, EventArgs e)
        {
            int iNo = dtAddress.Rows.Count + 1;
            dtAddress.Rows.Add(iNo, "", "", "B", "", "");
            this.lvAddress.DataSource = dtAddress;

            this.lvAddress.EditIndex = iNo - 1;
            this.lvAddress.DataBind();
            SetControlsStatus_Add("Add");
        }

        protected void lvAddress_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                ListViewItem lvi = e.Item;
                switch (e.CommandName)
                {
                    case "CancelAddNew":
                        this._cancelAddNewAdd();
                        this.lvAddress.DataBind();
                        break;
                    case "CancelUpdate":
                        if (string.IsNullOrEmpty(((TextBox)lvi.FindControl("lblAddress")).Text))
                        {
                            dtAddress.Rows.RemoveAt(e.Item.DataItemIndex);
                            ResetLineNo_Add();
                        }
                        this.lvAddress.EditIndex = -1;
                            this.lvAddress.DataSource = dtAddress;
                            this.lvAddress.DataBind();
                            SetControlsStatus_Add("Update");
                        break;

                    case "Update":
                        // update new data to dt
                        if (string.IsNullOrEmpty(((TextBox)lvi.FindControl("lblAddress")).Text)) return;

                        Label lblNo = (Label)lvi.FindControl("lblNo");
                        foreach (DataRow row in dtAddress.Rows)
                        {
                            if (row["No"].ToString().Equals(lblNo.Text)) // update currentrow into data table
                            {
                                row["Address"] = ((TextBox)lvi.FindControl("lblAddress")).Text;
                                row["CardCode"] = txtCardCode.Text;
                                row["Street"] = ((TextBox)lvi.FindControl("lblStreet")).Text;
                                row["AdresType"] = ((DropDownList)lvi.FindControl("ddlAdresType")).SelectedItem.Value;
                                row["StreetNo"] = ((TextBox)lvi.FindControl("lblStreetNo")).Text;
                                row["Building"] = ((TextBox)lvi.FindControl("lblBuilding")).Text;
                                break;
                            }
                        }
                        this.lvAddress.EditIndex = -1;
                        this.lvAddress.DataSource = dtAddress;
                        this.lvAddress.DataBind();
                        SetControlsStatus_Add("Update");
                        break;

                    case "DeleteItem":
                        // delete data and update dt
                        int i_idx = e.Item.DataItemIndex;
                        dtAddress.Rows.RemoveAt(i_idx);
                        this.lvAddress.EditIndex = -1;
                        ResetLineNo_Add();
                        this.lvAddress.DataSource = dtAddress;
                        this.lvAddress.DataBind();
                        SetControlsStatus_Add("Update");
                        break;

                    default: break;
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }

        protected void lvAddress_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            this.lvAddress.EditIndex = e.NewEditIndex;
            this.lvAddress.DataSource = dtAddress;
            this.lvAddress.DataBind();
            SetControlsStatus_Add("Edit");
        }

        protected void lvAddress_ItemInserted(object sender, ListViewInsertedEventArgs e)
        {
            _cancelAddNewAdd();
        }

        protected void lvAddress_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            Label TextBox = (Label)lvAddress.Items[e.ItemIndex].FindControl("lblAddress");
            if (string.IsNullOrEmpty(TextBox.Text))
            {
                e.Cancel = true;
                return;
            }
            this.lvAddress.EditIndex = -1;
            this.lvAddress.DataSource = dtAddress;
            this.lvAddress.DataBind();
        }

        protected void AddressPager_PreRender(object sender, EventArgs e)
        {
            lvAddress.DataSource = dtAddress;
            lvAddress.DataBind();
        }

        #endregion

        

    }
}